import tornado.web
import asyncmongo
import datetime
import hashlib

class UrlHandler(tornado.web.RequestHandler):
# To think about
# Sharding, do they do it now?
# Using the findAndModifyCommand? 
# Redis one instance per shard, on create make multiple instances all you will need so you won't have to reorder shards
# Background worker processes so non blocking
# Can we segment data per partner id?
# Lookup acamai

    @tornado.web.asynchronous
    def get(self, id):
        db = asyncmongo.Client(pool_id='mypool', host='localhost', port=27017, dbname='mydb')
#       idmd5 = hashlib.md5(id).hexdigest() 
        # make this find be able to read from replica's doesn't have to be perfect
#        db.urls.find_one( {'url': id}, callback=self._get_response)
        # make 'seen' a set and just push the datetime everytime, the first time it was seen is 'seen'[0]
        # mongodb has cappedCollections, this might be a nice feature to use...
        now = datetime.datetime.utcnow()
#        db.urls.update({'url': id},
#            {'$inc': {'total': 1}, '$set': {'lastseen': now},'$push': {'history': now}},
#            True, callback=self._update_response )
        query = { 'url': id }
        update = {'$inc': {'total': 1}, '$set': {'lastseen': now}, '$push': {'history': now}}
        db.urls.find_and_modify(query, update, upsert=True, new=False, callback=self._callback)

    def _callback(self, response, error):
        if error:
            raise tornado.web.HTTPError(500)

         # Optimization, could just have the upsert before the find. here just return now
        if not response:
            self.write(str(datetime.datetime.utcnow()))
            self.finish()
            return

        self.write(str(response))
        self.finish()
